'use strict';

import gulp from 'gulp';
import plumber from 'gulp-plumber';
import sass from 'gulp-sass';
import concat from 'gulp-concat';
import header from 'gulp-header';
import cache from 'gulp-cached';
import remember from 'gulp-remember';
import gulpif from 'gulp-if';
import uglify from 'gulp-uglify';

import del from 'del';
import source from 'vinyl-source-stream';
import buffer from 'vinyl-buffer';
import browserify from 'browserify';
import watchify from 'watchify';
import babelify from 'babelify';
import merge from 'merge-stream';
import minimist from 'minimist';

const knownOptions = {
  string: 'profile',
  default: { profile: 'terminus' }
};
const options = minimist(process.argv.slice(2), knownOptions);

const DEST = 'public';

gulp.task('clean', () => {
  del.sync([`${DEST}/**/*`]);
});

function browserifyCompile(watch, build) {
  let bundler = browserify('app/index.jsx', {
    cache: {},
    packageCache: {},
    paths: ['./node_modules', './app'],
    extensions: ['.jsx']
  }).transform(babelify);
  if (watch) {
    bundler = watchify(bundler);
  }
  function rebundle() {
    return bundler.bundle()
      .on('error', function errorHandler(err) { console.log(err); this.emit('end'); })
      .pipe(source('app.js'))
      .pipe(buffer())
      .pipe(header(`window._profile_ = '${options.profile}';`))
      .pipe(gulpif(build, uglify()))
      .pipe(gulp.dest(`${DEST}/scripts`));
  }

  if (watch) {
    bundler.on('update', () => {
      console.log('rebundling...');
      rebundle();
    })
    .on('time', (time) => { console.log(`bundle complete after ${time} ms `); });
  }

  return rebundle();
}
gulp.task('js', () => browserifyCompile(false, false));
gulp.task('js-build', () => browserifyCompile(false, true));
gulp.task('js-watch', () => browserifyCompile(true, false));

function cssCompile(watch, build) {
  const path = '{app/styles/[a-z]*.scss,app/comps/**/[a-z]*.scss}';
  if (watch) {
    gulp.watch(path, ['css']);
    gulp.watch('{app/styles/_*.{,scss,sass},app/comps/**/_*.scss}', () => {
      delete cache.caches.css;
      cssCompile(false, false);
    });
  }

  return gulp.src(path)
    .pipe(plumber())
    .pipe(cache('css'))
    // .pipe(header('@import "compass/functions";\n')) // make compass ruby functions useable
    // .pipe(sass({ includePaths: ['app/styles', 'app/comps', 'node_modules/compass-mixins/lib'] }).on('error', sass.logError))
    .pipe(sass({ includePaths: ['app/styles', 'app/comps'] }).on('error', sass.logError))
    .pipe(remember('css'))
    .pipe(concat('styles/app.css'))
    .pipe(gulp.dest(DEST));
}
gulp.task('css', () => cssCompile(false, false));
gulp.task('css-build', () => cssCompile(false, true));
gulp.task('css-watch', () => cssCompile(true, false));

function imageCompile(watch) {
  const path = 'app/images/**/*.{png,jpg,jpeg,gif}';
  if (watch) {
    gulp.watch(path, ['image']);
  }

  return gulp.src(path)
    .pipe(plumber())
    .pipe(gulp.dest(`${DEST}/images`));
}
gulp.task('image', () => imageCompile(false));
gulp.task('image-watch', () => imageCompile(true));

function viewCompile(watch) {
  const path = 'app/views/**/*.html';
  if (watch) {
    gulp.watch(path, ['view']);
  }

  return gulp.src(path)
    .pipe(gulp.dest(DEST));
}
gulp.task('view', () => viewCompile(false));
gulp.task('view-watch', () => viewCompile(true));

gulp.task('vendor', () => {
  const vendorCSS = gulp.src('node_modules/antd/dist/antd.css')
    .pipe(concat('styles/vendor.css'))
    .pipe(gulp.dest(DEST));

  // let fonts = gulp.src('node_modules/font-awesome/fonts/**/*', {base: 'node_modules/font-awesome'})
  //   .pipe(gulp.dest(DEST));

  return merge(vendorCSS);
});

gulp.task('watch', ['js-watch', 'css-watch', 'image-watch', 'view-watch', 'vendor']);

gulp.task('default', ['js', 'css', 'image', 'view', 'vendor']);

gulp.task('build', ['js-build', 'css-build', 'image', 'view', 'vendor']);
